package com.contract.spirit.ui.invite

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import com.contract.commonlib.util.ext.setOnSingleClickListener
import com.blankj.utilcode.util.KeyboardUtils
import com.contract.commonlib.base.BaseActivity
import com.contract.commonlib.view.CodeInputView
import com.contract.spirit.R
import com.contract.spirit.databinding.ActivityInputInviteCodeBinding
import com.contract.spirit.ui.login.LoginManger
import com.contract.spirit.ui.login.LoginViewModel

/**
 * @author: zhengjun
 * created: 2021/9/22
 * desc:
 */
class InputInviteCodeActivity : BaseActivity<ActivityInputInviteCodeBinding, LoginViewModel>() {
    private var inviteCode: String? = null
    override fun setContentView(): Int {
        return R.layout.activity_input_invite_code
    }

    override fun initData() {
        mViewModel.apply {
            phoneNumber.set(intent.getStringExtra("phone")!!)
            smsCode.set(intent.getStringExtra("code")!!)
        }
        editCodeCallBack()
        setClickListener()
    }

    private fun editCodeCallBack() {
        mBinding.etInviteCode.setOnInputListener(object : CodeInputView.OnInputListener {
            override fun onSucess(code: String?) {
                inviteCode = code
                KeyboardUtils.hideSoftInput(mContext)
                mBinding.btnSure.isEnabled = true
                mBinding.btnSure.setBackgroundResource(R.drawable.btn_common_gradient_orange_corner20)
            }

            override fun onInput() {
                inviteCode = ""
                mBinding.btnSure.isEnabled = false
                mBinding.btnSure.setBackgroundResource(R.drawable.btn_common_gradient_gray_corner20)
            }
        })
    }

    private fun setClickListener() {
        mBinding.btnSure.setOnSingleClickListener {
            login()
        }
        mBinding.tvSkip.setOnSingleClickListener {
            inviteCode = ""
            login()
        }
    }

    private fun login() {
        mViewModel.login(inviteCode)
    }

    override fun registerNecessaryObserver() {
        super.registerNecessaryObserver()
        LoginManger.registerLoginObervable(mViewModel, this)
    }

    companion object {
        fun launch(phone: String, code: String, activity: AppCompatActivity) {
            val intent = Intent(activity, InputInviteCodeActivity::class.java)
            intent.putExtra("phone", phone)
            intent.putExtra("code", code)
            activity.startActivity(intent)
        }
    }
}